import { readFileSync, readdirSync } from 'fs';

const svgTitle = /<svg([^>+].*?)>/;
const clearHeightWidth = /(width|height)="([^>+].*?)"/g;
const hasViewBox = /(viewBox="[^>+].*?")/g;
const clearReturn = /(\r)|(\n)/g;

// 创建symbol
function createSymbol(svg: string, id: string): string {
    return (
        svg
            .replace(clearReturn, '')
            // @ts-ignore
            .replace(svgTitle, (_$1, $2) => {
                let width = 0;
                let height = 0;
                // @ts-ignore
                let content = $2.replace(clearHeightWidth, (_s1, s2, s3) => {
                    if (s2 === 'width') width = s3;
                    else if (s2 === 'height') height = s3;
                    return '';
                });
                if (!hasViewBox.test($2)) content += `viewBox="0 0 ${width} ${height}"`;
                return `<symbol id="${id}" ${content}>`;
            })
            .replace('</svg>', '</symbol>')
    );
}

function readSvgDirectory(path: string, directory: string, prefix: string): Array<string> {
    const arr = [];
    // @ts-ignore
    arr.push(...readSvg(path + directory + '/', prefix + '-' + directory));
    return arr;
}

// 查找svg文件
function readSvg(path: string, prefix: string): Array<string> {
    const arr = [];
    const direntArray = readdirSync(path, { withFileTypes: true });
    for (const dirent of direntArray) {
        if (dirent.isDirectory()) {
            // @ts-ignore
            arr.push(...readSvgDirectory(path, dirent.name, prefix));
        } else {
            console.log('读取', path, prefix + '-' + dirent.name.replace('.svg', ''));
            const svg = readFileSync(path + dirent.name).toString();
            // @ts-ignore
            arr.push(createSymbol(svg, prefix + '-' + dirent.name.replace('.svg', '')));
        }
    }
    return arr;
}

// 加载 svg
export const loadSvg = (path: string, prefix: string) => {
    if (path === '') return;
    const res = readSvg(path, prefix);
    return {
        name: 'svg-transform',
        transformIndexHtml(dom: String) {
            return dom.replace(
                '<body>',
                `<body><svg style="position:absolute; width:0; height:0; visibility:hidden" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" >${res.join(
                    ''
                )}</svg>`
            );
        },
    };
};
